package net.work;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * UDP 接收 端A
 */
public class Work02ReceiverA {
    public static void main(String[] args) throws Exception {
        // 1.创建一个 DatagramPacket 对象，准备接收数据
        DatagramSocket socket = new DatagramSocket(8888);
        byte[] buf = new byte[1024];
        // 数据打包 --- 最大 64 KB
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        // 接收到数据
        System.out.println("接收端 等待接收问题 ");
        socket.receive(packet);

        // 拆包
        int length = packet.getLength();
        byte[] data = packet.getData();
        String msg = new String(data, 0, length);
        // 判断接收到的信息是什么
        String answer = "";
        if ("四大名著是哪些".equals(msg)) {
            answer = "《西游记》《水浒传》《红楼梦》《三国演义》";
        }else {
            answer = "你在说啥子";
        }

        // 回复消息给 B 端
        data = answer.getBytes();
        packet = new DatagramPacket(data, data.length, InetAddress.getLocalHost(), 9998);
        socket.send(packet); // 发送
        // 关闭资源
        socket.close();
        System.out.println("A端退出.....");
    }
}
